package reduce.fz.com.reduce.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.alibaba.fastjson.TypeReference;
import com.example.qingshengzheng.material.Text;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.abstracts.AbResponseListener;
import reduce.fz.com.reduce.adapter.ImageEditorPreviewAdapter;
import reduce.fz.com.reduce.bean.ExtraParam;
import reduce.fz.com.reduce.bean.ImageEditor;
import reduce.fz.com.reduce.bean.Pic;
import reduce.fz.com.reduce.bean.ServiceException;
import reduce.fz.com.reduce.bean.Team;
import reduce.fz.com.reduce.bean.TeamDynamic;
import reduce.fz.com.reduce.bean.User;
import reduce.fz.com.reduce.bean.WitnessCard;
import reduce.fz.com.reduce.bean.result.Result;
import reduce.fz.com.reduce.constant.PublishParams;
import reduce.fz.com.reduce.custom.LoadingDialog;
import reduce.fz.com.reduce.custom.MaterialDialog;
import reduce.fz.com.reduce.custom.MaterialDialogBuilder;
import reduce.fz.com.reduce.event.KeepEvent;
import reduce.fz.com.reduce.event.PubDynamicEvent;
import reduce.fz.com.reduce.photo.PhotoWallActivity;
import reduce.fz.com.reduce.service.TeamService;
import reduce.fz.com.reduce.service.preference.UserPreference;
import reduce.fz.com.reduce.util.HttpUtils;
import reduce.fz.com.reduce.util.ReduceLog;
import reduce.fz.com.reduce.util.ServiceBuilder;
import reduce.fz.com.reduce.util.TeamDynamicUtil;
import reduce.fz.com.reduce.util.ToastUtil;
import reduce.fz.com.reduce.util.oss.Oss;
import reduce.fz.com.reduce.util.oss.model.OssPic;
import reduce.fz.com.reduce.util.photo.PhotoSelect;
import reduce.fz.com.reduce.util.photo.SelectParam;

/**
 * 发布
 */

public class PubWitnessActivity extends BaseToolBarActivity implements ImageEditorPreviewAdapter.OnAddImageListener, View.OnClickListener {
    private GridView mGridView;
    private List<ImageEditor> mImageEditorList = new ArrayList<ImageEditor>();
    private ImageEditorPreviewAdapter mAdapter;
    private ArrayList<String> selectPaths;
    private TextView mTvFinish;
    private EditText mWitnessContent;
    private Oss oss = Oss.instance();
    private TeamService teamService = ServiceBuilder.builderTeamService(this);
    private Long teamid;
    private Team team;
    private LoadingDialog dialog;
    private TextView mWitnessSuggestion;
    public final static int WITNESS_EDIT = 1165;
    public Boolean isSuggestion = null;
    public MaterialDialog storyDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        team = (Team) getIntent().getSerializableExtra("team");
        teamid = team.teamid;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pub_witness);
        setToolbarTitle("发布见证");
        initWidget();
        initFinishBtn();
    }


    public void initFinishBtn() {

        mTvFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (selectPaths == null || selectPaths.isEmpty()) {
                    ToastUtil.showMessage("请至少上传一张图片!");
                    return;
                }

                dialog = new LoadingDialog(PubWitnessActivity.this);
                dialog.setTitle("准备提交!");
                dialog.show();
                oss.uploadPics(selectPaths, new Oss.OssUploadResponse() {
                    @Override
                    public void onSuccess(List<Pic> successPics, List<Pic> failedPics, List<Pic> all) {
                        List<String> pics = new ArrayList<String>();
                        for (int i = 0; i < successPics.size(); i++) {
                            pics.add(successPics.get(i).url);
                        }
                        submitInfo(pics, dialog);

                    }

                    @Override
                    public void onPrgress(int complete, int total) {
                        dialog.setTitle("上传图片中" + (complete + 1) + "/" + total);
                    }
                });

            }
        });
    }

    public List<Pic> toPics(List<String> pics) {
        List<Pic> temp = new ArrayList<Pic>();
        for (int i = 0; i < pics.size(); i++) {
            Pic pic = new Pic();
            pic.url = pics.get(i);
            temp.add(pic);
        }
        return temp;

    }

    public void submitInfo(List<String> pics, final LoadingDialog dialog) {
        dialog.setTitle("提交信息");
        final WitnessCard card = new WitnessCard();
        card.teamid = teamid;

        card.description = mWitnessContent.getText().toString();
        card.affimages = toPics(pics);
        teamService.pubWitness(card, new AbResponseListener<HashMap>(new TypeReference<Result<HashMap>>() {
        }) {
            @Override
            public void error(ServiceException e) {

            }

            @Override
            public void responseInfo(Result<HashMap> data) {
                if (dialog != null && dialog.isShowing())
                    dialog.dismiss();
                team.teamAttach.keepdays = Long.parseLong( data.getData().get("keepdays")+"");
                ToastUtil.showMessage("发布见证成功");
                EventBus.getDefault().post(new KeepEvent());
                User user = UserPreference.getUser();
                TeamDynamic teamDynamic = TeamDynamicUtil.pubWitness(user, card);
                EventBus.getDefault().post(new PubDynamicEvent(teamDynamic));
                /*if (team.teamAttach.keepdays >= team.teamAttach.targetset.keepDays) {
                    //达成目标
                    TeamDynamic complete = TeamDynamicUtil.completeTarget(user, team.teamAttach.targetset);
                    EventBus.getDefault().post(new PubDynamicEvent(complete));
                    pubstoryDialog();
                }*/
                Intent intent=new Intent();
                intent.putExtra("mekeepdays",team.teamAttach.keepdays);
                finish();

            }
        });
    }

    /**
     *发表故事
     */
    public void   pubstoryDialog() {
        if (storyDialog != null && storyDialog.isShowing()) return;
        storyDialog = MaterialDialogBuilder.getBuilder(this).content(R.string.story_create).positiveText(R.string.story_ok).negativeText(R.string.story_cancel).callback(new MaterialDialog.ButtonCallback() {
            @Override
            public void onPositive(MaterialDialog dialog) {
                super.onPositive(dialog);

            }

            @Override
            public void onNeutral(MaterialDialog dialogInterface) {
                super.onNeutral(dialogInterface);
                storyDialog.dismiss();
            }
        }).build();
    }



    public void pubStory() {
        SelectParam selectParam = new SelectParam();
        selectParam.selectMax = 10;
        selectParam.nextActivity = PubShareStoryActivity.class.getName();
        PhotoSelect select = PhotoSelect.instance(PubWitnessActivity.this, selectParam);
        ExtraParam params = new ExtraParam();
        params.set("teamid", team.teamid + "");
        select.selectPhoto(params);

    }


    public void initWidget() {
        mTvFinish = (TextView) findViewById(R.id.tv_finish);
        mWitnessSuggestion = (TextView) findViewById(R.id.witness_suggestin);
        mWitnessSuggestion.setOnClickListener(this);
        mWitnessContent = (EditText) findViewById(R.id.witness_content);
        mGridView = (GridView) findViewById(R.id.card_publish_selected_list);
        // 初始化自定义的适配器
        mAdapter = new ImageEditorPreviewAdapter(this, mImageEditorList, this);
        // 为mRecyclerView设置适配器
        mGridView.setAdapter(mAdapter);


    }

    public List<ImageEditor> toImageEditor(List<String> paths) {
        paths = filterDuplicate(paths);
        List<ImageEditor> editors = new ArrayList<ImageEditor>();
        for (int i = 0; i < paths.size(); i++) {
            ImageEditor temp = new ImageEditor();
            temp.originalPath = paths.get(i);
            editors.add(temp);
        }
        return editors;
    }

    public List<String> filterDuplicate(List<String> paths) {
        List<String> temp = new ArrayList<String>();
        if (selectPaths == null || selectPaths.isEmpty()) return paths;
        for (int i = 0; i < paths.size(); i++) {
            if (!selectPaths.contains(paths.get(i)))
                selectPaths.add(paths.get(i));
        }
        return selectPaths;

    }


    @Override
    public void initListener() {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SELECT_IMAGE:
                List<String> paths = data.getStringArrayListExtra(PhotoWallActivity.IMAGE_SELECT_RESULT);
                selectPaths = (ArrayList<String>) filterDuplicate(paths);
                mImageEditorList.clear();
                mImageEditorList.addAll(toImageEditor(selectPaths));
                mAdapter.replaceImage(mImageEditorList);
                break;
            case WITNESS_EDIT:
                if (data == null) return;
                break;
            default:
                break;
        }


    }

    private final static int SELECT_IMAGE = 100;

    public void selectPic(int maxCount) {
        Intent intent = new Intent(this, PhotoWallActivity.class);
        intent.putExtra(PublishParams.MAX_SELECT_COUNT, maxCount);
        intent.putExtra(PublishParams.HAS_SELECT_LIST, selectPaths);
        startActivityForResult(intent, SELECT_IMAGE);
    }


    @Override
    public void needSelectImage(int maxCount, int needCount) {
        selectPic(maxCount);

    }

    @Override
    public void onEditorClick(int position) {

    }

    @Override
    public void onRemoveImage(int position) {
        if (position < mImageEditorList.size())
            mImageEditorList.remove(position);
        if (position < selectPaths.size())
            selectPaths.remove(position);
    }

    public void forwardEdit() {
        if (isSuggestion) {
            ToastUtil.showMessage("每天只能发送一次见证建议!");
            return;
        }
        Intent intent = new Intent(this, WitSuggestionEditActivity.class);
        startActivityForResult(intent, WITNESS_EDIT);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.witness_suggestin:
                forwardEdit();
                break;
            default:
                break;
        }
    }
}
